<?php

namespace app\admin\controller;


use app\admin\controller\Authorized;
use Org\Nx\Data;
use think\Db;
use think\Session;


class Category extends Authorized
{
    public function _initialize(){parent::_initialize();}

    public function index()
    {
        return $this->fetch();
    }


    public function getList()
    {
        $rows = Db::table('category')->order('id')->select();
        return json($rows);
    }

    public function add()
    {
        $post_data = $this->request->post();
        if($post_data){
            $post_data['created_at'] = $post_data['updated_at'] = time();
            $id =Db::table('category')->insertGetId($post_data);
            if (false === $id) {
                Db::table('article')->rollback();
                return json(['code' =>1,'count' =>0,'msg' =>'添加失败','data'=>'']);
            } else {
                Db::table('article')->commit();
                return json(['code' =>0,'count' =>0,'msg' =>'添加成功','data'=>'']);
            }


        }
        $category_list = Db::table('category')->where('pid',0)->order('id')->select();
        $this->assign('category_list', $category_list);

        return $this->fetch();
    }

    public function edit()
    {
        $post_data = $this->request->post();
        if($post_data){
            $post_data['updated_at'] = time();
            $result = Db::table('category')->where(array('id' =>$post_data['id']))->update($post_data);
            if (false === $result) {
                return json(['code' =>1,'msg' =>'修改失败']);

            } else {
                return json(['code' =>0,'msg' =>'修改成功']);
            }
        }
        $category = Db::table('category')->where(array('id' => input('id')))->find();
        $category_list = Db::table('category')->where('pid',0)->order('id')->select();
        $this->assign('category', $category);
        $this->assign('category_list', $category_list);

        return $this->fetch();
    }


    public function del()
    {
        $post_data = $this->request->post();
        if($post_data){
            $result = Db::table('category')->where('id', input('id'))->delete();
            if (false === $result) {
                return json(['code' =>1,'msg' =>'删除失败']);
            } else {
                return json(['code' =>0,'msg' =>'删除成功']);
            }
        }
    }
}